$(function () {
    //控制音乐
    var musiCplay = true; //音乐是否开启
    function musicplay(name) {
        musiCplay = true;
        document.addEventListener("WeixinJSBridgeReady", function () {
            $(name)[0].play();
        }, false);
        $(name).on('ended', function () {

            $('.bg_music')[0].play();
        });
        $('.music_btn').click(function () {

            if (musiCplay) {
                $(name)[0].pause();
                $('.music_btn').removeClass('music_arrow');

                $(".music_btn").attr("src", 'images/end.png');
            } else {
                $(name)[0].play();
                $('.music_btn').addClass('music_arrow');
                $(".music_btn").attr("src", 'images/mp3.png');
            }
            musiCplay = !musiCplay;
        });

    }
    musicplay('.bg_music');

    var imageList = [ //小图
        './images/myIcon/P4-P9_07.png',
        './images/myIcon/P4-icon_05.png',
        './images/myIcon/P4-icon_07.png',
        './images/myIcon/P4-icon_09.png',
        './images/myIcon/P4-P91_05.png',
        './images/myIcon/P4-icon1_05.png'
    ];
    var bigImageList = [ //大图
        './images/myIcon/P4-1_01.png',
        './images/myIcon/P4-2_02.png',
        './images/myIcon/P4-3_02.png',
        './images/myIcon/P4-4_02.png',
        './images/myIcon/P4-5_02.png',
        './images/myIcon/P4-6_02.png'
    ];

    //图片框大图

    for (var i = 0; i < bigImageList.length; i++) {
        $('#bigImageList').children().eq(i).children().attr('src', bigImageList[i])
    }
    //背景框小图
    for (var i = 0; i < imageList.length; i++) {
        $('#bottomList').children().eq(i).children().attr('src', imageList[i])
    }

    $('.up').hide();
    $('.down').hide();
    $('.isLeft').hide();
    $('.baoCun').hide();
    //$('.div4').addClass('swiper-no-swiping')
    $('.div5').hide();
    $('.he-cheng').hide();
    // $('.myImageItem').hide();
    var index = 0; //当前活动块的index
    var isVideo = false; //当前视频是否播放状态
    var isPhoto = false; //是否初始化相机
    var isBaoCun = false; //是否保存图片到相册
    //分页效果
    var swiper1 = new Swiper('.swiper1', {
        direction: 'vertical',
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        observer: true,
        observeParents: true,
        onSlideChangeEnd: function (swiper) {
            swiper.update(); //swiper更新
        }
    });
    var swiper2 = new Swiper('.swiper2', {
        direction: 'vertical',
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        observer: true,
        observeParents: true,
    });
    $('.up').click(function () { //上一页
        swiper2.slideTo(--index);
        isHidden(index);
        // noUpPage(index,swiper1);
        console.log(index)
    })
    $('.isLeft').click(function () { //左前头往上翻页
        // var swiper2 = new Swiper('.swiper2', {
        //     direction: 'vertical',
        //     pagination: {
        //         el: '.swiper-pagination',
        //         clickable: true,
        //     },
        //     observer:true,
        //     observeParents:true,
        // });
        swiper2.slideTo(--index);
        isHidden(index);
        console.log(index)
    })
    $('.down').click(function () { //下一页
        swiper2.slideTo(++index);
        isHidden(index);
        // noUpPage(index,swiper1);
        console.log(index)
    })

    //通过触摸屏幕获取当前活动块的index
    swiper1.on('slideChangeTransitionEnd', function () {
        console.log(swiper1.activeIndex);
        index = swiper1.activeIndex;
        isHidden(index);
        // noUpPage(index,swiper1);
        console.log('滑动');
        console.log('isPhoto===' + isPhoto);
    });

    //播放器下面的下一页跳转按钮
    $('.div3 .button').click(function () {
        var swiper3 = new Swiper('.swiper3', {
            direction: 'vertical',
            observer: true,
            observeParents: true,
        });
        swiper3.slideTo(++index);
        isHidden(index);
        console.log(index)
    })
    var imageIndex = 0; //背景框轮播索引
    var imageId = imageIndex;

    //照片框轮播图
    var bigImageListSwiper = new Swiper('.bigImageListSwiper', {
        loop: true,
        slidesPerView: 1,
        clickable: true,
        pagination: {
            el: '.pagination',
            dynamicBullets: false,
        },
    });

    //如果你在swiper初始化后才决定使用clickable，可以这样设置
    bigImageListSwiper.params.pagination.clickable = true;
    //此外还需要重新初始化pagination
    bigImageListSwiper.pagination.destroy()
    bigImageListSwiper.pagination.init()
    bigImageListSwiper.pagination.bullets.eq(0).addClass('swiper-pagination-bullet-active');
    //背景选择框
    var imageListSwiper = new Swiper('.imageListSwiper', {
        loop: true,
        slidesPerView: 5,
        spaceBetween: 80,
        observer: true,
        observeParents: true,

    })

    $('.bottomList .item').each(function () {
        $(this).click(function () {
            imageIndex = $(this).attr('id');
            console.log(bigImageListSwiper.slides[0])
            console.log('点击了===' + imageIndex)
            bigImageListSwiper.slideTo(imageIndex);
            console.log('合成图片3333+=====' + imageIndex)
            // beiJingKuang(imageIndex);
            // myPicture();
        })
    })
    bigImageListSwiper.on('slideChangeTransitionEnd', function () {
        imageId = bigImageListSwiper.realIndex;
        console.log('触摸了11111===' + imageId)
    })

    //视频播放
    $('.video').click(function () {
        if (isVideo == false) { //视频暂停状态
            $('#videoImage').hide();
            $('#videoBtn').hide();
            $('#video')[0].play();
            isVideo = !isVideo;
            $('.bg_music')[0].pause();
            //isVideo=true;
            console.log('isVideo==' + isVideo)
        } else if (isVideo == true) {
            $('#video')[0].pause();
            $('#videoBtn').show();
            $('.bg_music')[0].play();
            isVideo = !isVideo;
            //isVideo=false;
            console.log('isVideo==' + isVideo)
        }
    })

    //监听video暂停
    $('#video')[0].onpause = function () {
        isVideo = false;
        $('.bg_music')[0].play();
    }
    //监听video开始播放
    $('#video')[0].onplaying = function () {
        isVideo = false;
        $('.bg_music')[0].pause();
    }

    //手机兼容性判断
    //获取浏览器的userAgent,并转化为小写
    var ua = navigator.userAgent.toLowerCase();
    //判断是否是苹果手机，是则是true
    var isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);
    if (isIos) {
        $(".picture-input").removeAttr("capture");
    };

    var orientation = 1; //图片旋转值
    //拍照
    $("#picture-input").change(function () {
 
        if (isPhoto == false) {
            isPhoto = true;
            $('.myImageItem').css({
                'left': 0,
                'top': 0
            });
        }
        swiper1.init();
        heChengButton(isPhoto);
        onFileChange(this, "myImageItem");

    });

    //拖动照片
    // $('.myImageItem')
    $('.bigImageList').mousedown(function (e) {

        //alert('开始拖动。。。。')
    })
    //长按图片并保存到相册
    var timeout = 0;
    $(".canvas-img").mousedown(function () {
        timeout = setTimeout(function () {
            var imgSrc = $('.canvas-img').attr('src')
            isBaoCun(imgSrc);
        }, 1000);
    });

    $(".canvas-img").mouseup(function () {
        clearTimeout(timeout);
    });

    $(".canvas-img").mouseout(function () {
        clearTimeout(timeout);
    });
    var orientation = 1;
    //合成图片
    $('#heCheng').click(function () {

        $('.baoCun').hide();
        $('.div5').show();
        $('.top-div').hide();
        $('.up').hide();
        $('.isLeft').hide();
        $('.down').hide();

        var file = $("#picture-input")[0].files[0];
        EXIF.getData(file, function () {
            EXIF.getAllTags(this);
            orientation = EXIF.getTag(this, 'Orientation'); //这个Orientation 就是我们判断需不需要旋转的值了，有1、3、6、8  
            //alert('orientation333====' + orientation)
            heCheng(imageId + 1, orientation);
        });

        console.log('合成图片2222=====' + imageId)

    });
})
//获取图片base64的值
function getBase64(imgDOM) {
    var canvas = document.createElement("canvas");
    canvas.width = imgDOM.width;
    canvas.height = imgDOM.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgDOM, 0, 0, imgDOM.width, imgDOM.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL // return dataURL.replace("data:image/png;base64,", ""); 
}
//禁止第3、4页往回退
function noUpPage(index, swiper) {
    if (index == 3 || index == 2) {
        swiper.allowSlidePrev = false;
    }
    console.log(index)
}

//照片显示
function myPicture() {
    $('.div5 .picture').attr('src', function () {
        return $('.myImageItem').attr('src');
    })
}
//箭头显示隐藏效果
function isHidden(index) {
    //如果为第1页或第5页，则上下箭头隐藏
    //如果为第4页，则上下箭头隐藏，左箭头显示
    if (index == 0) {
        $('.up').hide();
        $('.isLeft').hide();
        $('.down').hide();
    } else if (index == 1) {
        $('.up').show();
        $('.isLeft').hide();
        $('.down').show();
    } else if (index == 2) {
        $('.up').show();
        $('.isLeft').hide();
        $('.down').hide();
    } else if (index == 3) {
        $('up').hide();
        $('.isLeft').show();
        $('down').hide();
    } else if (index == 4) {
        $('.up').hide();
        $('.isLeft').hide();
        $('#down').hide();
    }
}


/**
 * 选中图片时的处理
 * @param {*} fileObj input file元素
 * @param {*} el //选中后用于显示图片的元素class
 * @param {*} btnel //未选中图片时显示的按钮区域ID
 */
function onFileChange(fileObj, el) {

    var windowURL = window.URL || window.webkitURL;
    var dataURL;
    var imgObj = $('.' + el)[0];
    //document.getElementById(btnel).style.display="none";
    imgObj.style.display = "block";
    if (fileObj && fileObj.files && fileObj.files[0]) {
        dataURL = windowURL.createObjectURL(fileObj.files[0]);
        imgObj.src = dataURL;
    } else {
        dataURL = fileObj.value;
        imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
        imgObj.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
    }
}

/**
 * 将图片压缩后返回base64格式的数据
 * @param {*} image img元素
 * @param {*} width 压缩后图片宽度
 * @param {*} height 压缩后图片高度
 * @param {*} qua //图片质量1-100
 */
function compressImageTobase64(image, width, height, qua) {
    var quality = qua ? qua / 100 : 0.8;
    var canvas = document.createElement("canvas"),
        ctx = canvas.getContext('2d');
    var w = image.naturalWidth,
        h = image.naturalHeight;
    canvas.width = width || w;
    canvas.height = height || h;
    ctx.drawImage(image, 0, 0, w, h, 0, 0, width || w, height || h);
    var data = canvas.toDataURL();
    return data;
}


//图片合成
function heCheng(imageId, orientation) {
    //alert('orientation444===' + orientation)

    var imgUrlList = ['./images/1.png', './images/2.png', './images/3.png', './images/4.png', './images/5.png', './images/6.png'];
    var canvas = document.createElement("canvas");
    canvas.width = 375;
    canvas.height = 667;
    console.log('canvas.widt===' + canvas.width)
    var context = canvas.getContext('2d');
    context.rect(0, 0, canvas.width, canvas.height);
    context.fillStyle = '#fff';
    context.fill();
    var image1 = new Image();
    image1.src = $('.myImageItem').attr('src');  
    //image2.src = $('.bigImageList .item').eq(imageId).children().attr('src');
    //alert("image2.src===" + image2.src)
    image1.crossOrigin = "Anonymous"
    image1.src = compress(image1);
    console.log('合成图片===' + orientation)
   
    image1.onload = function () {
        //isIos系统照片合成会对原始照片旋转
        var width = image1.width;
        var height = image1.height;
        var degree = 0;
        if (orientation == 1) {
            context.save();
            context.rotate(degree);
            context.drawImage(this, 0, 0);
            //alert('被执行1111')
        } else if (orientation == 8) { //逆时针90度
            step = 1;
            degree = step * 90 * Math.PI / 180;
            context.save();   //保存状态
            context.rotate(degree);
            context.drawImage(this, -width, -height);
            //alert('被执行---逆时针90度')
        } else if (orientation == 6) { //顺时针90度
            var degree = 90 * Math.PI / 180;
            context.save();
            context.rotate(degree);
            context.drawImage(this, 0, -(width * 1.05) / 2, width * 0.7, height * 0.7);
            //alert('被执行---顺时针90度')
        } else if (orientation == 3) { //旋转180度
            var degree = 180 * Math.PI / 180;
            context.save();
            context.rotate(degree);
            context.drawImage(this, -(width * 1.2) / 2, -(height * 1.6) / 2, width * 0.7, height * 0.7);
            //alert('被执行----旋转180度')
        }
       
        //context.drawImage(image1, 0, 0, 375, 667);
        var image2 = new Image();
        image2.src = imgUrlList[imageId];
        image2.crossOrigin = "Anonymous";
        image2.onload = function () {
            context.restore();   //恢复初始状态
            context.drawImage(image2, 0, 0, 375, 667);
            var base64 = canvas.toDataURL('image/png');
            var img = $('.canvas-img');
            img.attr('src', base64)
        }
       
    };
 
}

//是否保存图片到相册
function isBaoCun(imgSrc) {
    $('.baoCun').show();
    //保存图片
    $('.left-btn').click(function () {
        plus.gallery.save(imgSrc);
        $('.baoCun').hide();
    });

    $('.right-btn').click(function () {
        $('.baoCun').hide();
    })
}
//合成按钮
function heChengButton(isPhoto) {
    if (isPhoto == true) {
        $('.he-cheng').show();
    } else {
        $('.he-cheng').hide();
    }
    console.log('isPhoto222======' + isPhoto)
}

//不失真压缩
function compress(img) {
    // 默认按比例压缩
    var w = img.width,
        h = img.height,
        scale = h / w;

    w = 720;
    h = parseInt(w * scale);

    console.log(scale);
    console.log('原W：' + img.width + '后：' + w);
    console.log('原H：' + img.height + '后：' + h);

    // var quality = 0.7; // 默认图片质量为0.7
    var quality = 1;

    //生成canvas
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    // 创建属性节点
    var anw = document.createAttribute("width");
    anw.nodeValue = w;
    var anh = document.createAttribute("height");
    anh.nodeValue = h;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(img, 0, 0, w, h);


    var newImg = canvas.toDataURL("image/jpeg", quality);

    console.log('压缩前-----：' + (img.src.length / 1024) + "KB");
    console.log('压缩后：' + (newImg.length / 1024) + "KB");
    console.log('压缩率：' + ~~(100 * (img.src.length - newImg.length) / img.src.length) + "%");

    // quality值越小，所绘制出的图像越模糊
    return newImg;

}
